package com.zx.mes.hyl.security.core.validate.code.sms.impl;

import com.zx.mes.hyl.security.core.properties.SecurityConstants;
import com.zx.mes.hyl.security.core.validate.code.ValidateCode;
import com.zx.mes.hyl.security.core.validate.code.ValidateCodeRepository;
import com.zx.mes.hyl.security.core.validate.code.ValidateCodeType;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.web.context.request.ServletWebRequest;

/**
 * 校验码存取器 默认实现
 * @author huayunlong
 * @date 2018-6-2
 */
public class DefaultValidateCodeRepository implements ValidateCodeRepository {

    private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();

    @Override
    public void save(ServletWebRequest request, ValidateCode code, ValidateCodeType type) {
        /* 将随机数存至 session 中 **/
        sessionStrategy.setAttribute(request, SecurityConstants.DEFAULT_SESSION_IMAGE_KEY, code);
    }

    @Override
    public ValidateCode get(ServletWebRequest request, ValidateCodeType type) {

        return (ValidateCode) sessionStrategy.getAttribute(request,
                SecurityConstants.DEFAULT_SESSION_IMAGE_KEY);
    }

    @Override
    public void remove(ServletWebRequest request, ValidateCodeType type) {
        sessionStrategy.removeAttribute(request, SecurityConstants.DEFAULT_SESSION_IMAGE_KEY);
    }
}
